package org.xiangfei.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.xiangfei.client.exception.AuthException;
import org.xiangfei.client.handler.MessageClientInitializer;
import org.xiangfei.client.service.LoginService;
import org.xiangfei.codec.bean.Auth;
import org.xiangfei.codec.bean.XFMessage;

/**
 * 
 * @author feesx@qq.com
 * @version 1.0
 *
 */
public class XFClient {
    private String routeHost = null;
    private int routePort = 0;
    private static EventLoopGroup group = new NioEventLoopGroup();
    private static Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class);
    private static Channel channel = null;

    public XFClient(String routeHost, Integer routePort) {
        this.routeHost = routeHost;
        this.routePort = routePort;
    }

    public void connection(XFClientOptions options) throws Exception {

        try {
            // 权限验证，返回userToken，全服务器唯一，调用auth服务
            // 链接成功，调用心跳服务，更新用户状态
            // 发送消息，判断是否链接成功?

            Auth auth = new Auth();
            auth.setUserName(options.getUserName());
            auth.setPassword(options.getPassword());
            if (login(auth)) {
                bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
                System.out.println(options.getCallback() + "==");
                bootstrap.handler(new MessageClientInitializer(options.getCallback()));
                ChannelFuture channelFuture = bootstrap.connect(routeHost, routePort);
                channelFuture.addListener(new ChannelFutureListener() {
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            System.out.println("client connected");
                        } else {
                            System.out.println("server attemp failed");
                            future.cause().printStackTrace();
                        }
                    }
                });
                channel = channelFuture.sync().channel();
                // XFMessage message = new XFMessage();
                // message.setCreateDate(new Date());
                // message.setMessage("hello server");
                // message.setFromUserId("1");
                // message.setToUserId("2");
                // channel.writeAndFlush(message);
                // channel.closeFuture().sync();

            } else {
                throw new AuthException("0", "auth fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // group.shutdownGracefully();
        }
    }

    public void close() {
        try {
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        group.shutdownGracefully();
    }

    public void publish(String sendUserId, String receiveUserId, String content) {
        XFMessage message = new XFMessage();
        message.setCreateDate(new Date());
        message.setMessage(content);
        message.setSendUserId(sendUserId);
        message.setReceiveUserId(receiveUserId);
        ChannelFuture channelFuture = channel.writeAndFlush(message);
        channelFuture.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    System.out.println("write data success");
                } else {
                    System.out.println("write data error");
                    future.cause().printStackTrace();
                }
            }
        });

    }

    private boolean login(Auth auth) {
        LoginService loginService = new LoginService();
        return loginService.auth(auth);
    }

    public static void main(String[] args) throws IOException {
        XFClient client = new XFClient("localhost", 8000);
        XFClientOptions options = new XFClientOptions();
        options.setUserName("admin");
        options.setPassword("123456");
        options.setCallback(new XFCallback() {
            public void connectionLost(Throwable cause) {
                // TODO Auto-generated method stub
            }
            public void deliveryComplete() {
                // TODO Auto-generated method stub
            }
            public void messageArrived(XFMessage message) {
                System.out.println("client receiveMsg = " + message.getSendUserId() + ":" + message.getMessage());
            }
        });
        try {

            client.connection(options);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 发送消息
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        while(true) {    
            String msg = in.readLine();
            System.out.println(msg);
            String[] msgArray = msg.split(",");
            client.publish(msgArray[0], msgArray[1], msgArray[2]);
        }
       
        // 发送消息
        //client.publish();
        //client.publish();
    }

}
